package com.zhuanghdong.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.zhuanghdong.utils.JwtHelper;
import com.zhuanghdong.utils.Result;
import com.zhuanghdong.utils.ResultCodeEnum;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * LoginProtectInterceptor登录保护拦截器
 * 用来对每一次访问，来检验是否过了登录有效时间
 */
@Component
public class LoginProtectInterceptor implements HandlerInterceptor{
    @Autowired
    private JwtHelper jwtHelper;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");
        if(StringUtils.isEmpty(token)||jwtHelper.isExpiration(token)){
            Result result=Result.build(null, ResultCodeEnum.NOTLOGIN);
            ObjectMapper objectMapper = new ObjectMapper();
            String json = objectMapper.writeValueAsString(result);
            response.getWriter().print(json);
            return false;
        }else {
            return true;
        }
    }
}